package javaidiot;

import java.sql.*;

/**
 *
 * @author Master
 */
public class Select extends SQLConnection {

    private static ResultSet result;
    public String[][] resultArray;

    public Select(String driver, String server, String props, String query) {
        super(driver, server, props);
        result = query(query);
        resultArray = toArray();
    }

    /**
     * Supportive method for toArray()
     * Extends array by 1
     */
    private static String[][] resizeArray(String[][] array) {
        String[][] t = new String[(array.length + 1)][array[0].length];
        for (int i = 0; i < array.length; i++) {
            System.arraycopy(array[i], 0, t[i], 0, array[i].length);
        }
        array = new String[t.length][t[0].length];
        for (int i = 0; i < array.length; i++) {
            System.arraycopy(t[i], 0, array[i], 0, array[i].length);
        }
        return array;
    }

    /**
     * Method transfers database output to two-dimensional array
     * Output is stored in static resultArray to provide access for View
     */
    private static String[][] toArray() {
        int count = 0;
        String[][] array = null;
        try {
            ResultSetMetaData rsmd = result.getMetaData();
            if (rsmd != null) {
                int numberOfColumns = rsmd.getColumnCount();
                array = new String[1][numberOfColumns];
                while (result.next()) {
                    if (count > 0) {
                        array = resizeArray(array);
                    }
                    // Column indexes are started from 1
                    for (int i = 1; i <= numberOfColumns; i++) {
                        array[count][i - 1] = result.getString(i);
                    }
                    count++;
                }
            }
        } catch (SQLException e) {
            debug(e.getMessage());
        }
        return array;
    }

    private ResultSet query(String query) {
        ResultSet rs = null;
        Statement stmt = null;

        try {
            stmt = connection.createStatement();
        } catch (SQLException e) {
            debug(e.getMessage());
        }
        try {
            rs = stmt.executeQuery(query);
            result = rs;
        } catch (SQLException e) {
            debug(e.getMessage());
        }
        return rs;
    }
}
